<script setup lang="ts">
import { onMounted, ref,watchEffect,toRaw } from 'vue'
import { MoreHorizontalIcon } from 'lucide-vue-next'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'
import { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem } from '@/components/ui/menubar'
import { Input } from '@/components/ui/input'

import CommonInputModule from '../common-input-module.vue'
import CommonKnowledgeModule from '../common-knowledge-module.vue'
import StaticOutputModule from '../static-output-module.vue'

import { LLMNodeData, LLMNodeEvents } from './index'
import storeMap from '@/pina/index'
import type { NodeProps } from '@vue-flow/core'
import { useLLMStore } from '@/pina/LLMStore'
import {typesOptions} from '@/lib/dict'
const props = defineProps<NodeProps<LLMNodeData, LLMNodeEvents>>()

// const title = ref(props.data.title)
const isEditTitle = ref(false)
const useKnowLedge = storeMap.useKnowLedgeStore();
const data = useKnowLedge.template.data;

const { title } = data;
const node = useNode()
const { removeNodes, nodes, addNodes } = useVueFlow()

//知识库暂时写死了类型和label
function transformData(node: any): any {
  const name = node.name?'name':'label'
  const transformedNode: any = {
    label: node[name],  // 替换 name 为 label
    type: 'Array<String>',
  };
  return transformedNode;
}

function parseIfJson(str:string){
  // 检查是否为字符串
  if (typeof str === 'string') {
    try {
      // 尝试解析为 JSON
      const parsed = JSON.parse(str);
      
      // 如果解析成功并且是对象，返回解析后的对象
      if (typeof parsed === 'object' && parsed !== null) {
        return parsed;
      }
    } catch (error) {
      // 如果解析失败，说明它只是一个普通字符串
      return str;
    }
  }
  
  // 如果已经是对象或者非字符串类型，直接返回
  return str;
}

const outputData = parseIfJson(data.output[0].value)?.map((item:any)=>{
  return transformData(item)
});
function handleClickDeleteBtn() {
  removeNodes(node.id)
}

function handleClickDuplicateBtn() {
  const { type, position, label, data } = node.node
  const newNode = {
    id: (nodes.value.length + 1).toString(),
    type,
    position: {
      x: position.x + 100,
      y: position.y + 100
    },
    label,
    data
  }
  addNodes(newNode)
}

const settingNodeData = ()=>{
  const {title,description,input,output} =useKnowLedge.template.data;
    const { name,strategy,topK,similarityThreshold,title:Kbasetitle} = useKnowLedge.template.data.kbase
    if(node.node.data){
      node.node.data = {
      //给node节点添加到json当中
        // id: useKnowLedge.template.id,
        // type: useKnowLedge.template.type,
        title,description,
        "kbase": {
          name,title:Kbasetitle,strategy,topK:topK[0],similarityThreshold:similarityThreshold[0]
        },
        input,
        output:[
        { 
            name:'output',
            type:'5',
            value:typeof data.output[0].value=='string'?data.output[0].value:JSON.stringify(data.output[0].value) //知识库节点默认输出
          }
        ],
      }
    }
}
watchEffect(() => {
  if (node.connectedEdges && node.connectedEdges.value.length > 0) {
    settingNodeData()
    //update node data
  }
  // const edgeObject =  node.connectedEdges.value.find(item=>item.target==node.id)
  // if(!edgeObject){
  //   useKnowLedge.clearData()
  // }
})
onMounted(() => {
  settingNodeData()
})
</script>

<template>
  <div class="rounded-sm border border-gray-200 bg-white p-3 shadow-md">
    <Handle type="target" :position="Position.Left" />
    <div class="flex flex-col gap-y-4">
      <div class="flex justify-between">
        <div class="flex gap-x-2">
          <img src="~@/assets/images/icon_Knowledge.png" class="mt-1 h-4 w-4" alt="Knowledge icon" />
          <div class="flex flex-col gap-y-1">
            <Input v-model="data.title" class="h-5" v-if="isEditTitle" @blur="() => (isEditTitle = false)" />
            <h3 class="text-base" v-else>{{ data.title }}</h3>
            <p class="text-sm text-gray-500">知识库</p>
          </div>
        </div>

        <Menubar class="border-none">
          <menubar-menu>
            <menubar-trigger>
              <more-horizontal-icon />
            </menubar-trigger>
            <menubar-content>
              <menubar-item @click="handleClickDuplicateBtn"> 复制 </menubar-item>
              <menubar-item @click="handleClickDeleteBtn"> 删除 </menubar-item>
              <menubar-item @click="isEditTitle = true"> 重命名 </menubar-item>
            </menubar-content>
          </menubar-menu>
        </Menubar>
      </div>

      <span class="text-sm text-gray-500"
        >{{
          data.description
        }}</span
      >

      <div class="grid gap-y-3">
        <common-input-module :data="data.input" :staticNameKey="[]" storeId="useKnowLedgeStore" />
        <common-knowledge-module :data="data" />
        <static-output-module
          tip="The output list is the information that best match the input parameters, recalled from all selected knowledge"
          :data="outputData"
        />
      </div>
    </div>
    <Handle type="source" :position="Position.Right" />
  </div>
</template>
